const { Service } = require('egg')
const cheerio = require('cheerio')
const { RSAencrypt } = require('../utils/RSA')

module.exports = class LoginService extends Service {
  /**
   * * 模拟登录，获取cookie
   * @return {setCookie: string, status: number} **
   */
  async getCookie() {
    try {
      const { ctx } = this
      const { sid, pwd } = ctx.data

      /* * 1. 请求登录页面，获取lt，warn，execution，_eventId */
      const homeUrl = 'https://cas.hutb.edu.cn/lyuapServer/login?service=http%3A%2F%2Fjwgl.hutb.edu.cn%2F'
      const homeRes = await ctx.curl(homeUrl, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
      })
      const setCookie = homeRes.headers['set-cookie'] ? homeRes.headers['set-cookie'].map((e) => e.split(';')[0]).join(';') : ''
      const $ = cheerio.load(homeRes.data.toString())
      const lt = $('input[name=lt]').attr().value
      const warn = $('input[name=warn]').attr().value
      const execution = $('input[name=execution]').attr().value
      const _eventId = $('input[name=_eventId]').attr().value
      /* end */

      /* * 2. 请求登录接口 */
      // eslint-disable-next-line max-len
      const password = RSAencrypt(pwd, '00f0d1b6305ea6256c768f30b6a94ef6c9fa2ee0b8eea2ea5634f821925de774ac60e7cfe9d238489be12551b460ef7943fb0fc132fdfba35fd11a71e0b13d9fe4fed9af90eb69da8627fab28f9700ceb6747ef1e09d6b360553f5385bb8f6315a3c7f71fa0e491920fd18c8119e8ab97d96a06d618e945483d39d83e3a2cf2567')
      const loginUrl = 'https://cas.hutb.edu.cn/lyuapServer/login?service=http%3A%2F%2Fjwgl.hutb.edu.cn%2F'
      const loginRes = await ctx.curl(loginUrl, {
        method: 'POST',
        data: {
          username: sid,
          password,
          warn,
          lt,
          execution,
          _eventId,
        },
        headers: {
          Cookie: setCookie,
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
      })
      /* end */
      if (loginRes.status !== 302) { return { setCookie: '', status: loginRes.status } }

      /**
       * * 3. 登录验证成功，第一次重定向
       * ! 观察发现此次请求的Cookie为最终所需Cookie，记录并在之后两次重定向请求中使用
       */
      const reUrl1 = loginRes.headers.location
      const res1 = await ctx.curl(reUrl1, {
        method: 'GET',
        headers: {
          Cookie: setCookie,
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
      })
      const resultCookie = res1.headers['set-cookie'] ? res1.headers['set-cookie'].map((e) => e.split(';')[0]).join(';') : ''
      /* end */

      /* * 4. 登录验证成功，第二次重定向 */
      const reUrl2 = loginRes.headers.location
      const res2 = await ctx.curl(reUrl2, {
        method: 'GET',
        headers: {
          Cookie: resultCookie,
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
      })
      /* end */

      /* * 5. 登录验证成功，第三次重定向 */
      const reUrl3 = res2.headers.location
      await ctx.curl(reUrl3, {
        method: 'GET',
        headers: {
          Cookie: resultCookie,
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
      })
      /* end */

      return { setCookie: resultCookie, status: loginRes.status }
    } catch (err) {
      console.log(err)
      return { setCookie: '', status: 500 }
    }
  }
}
